package com.video.data.utils;

import com.video.data.model.HttpModel;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.*;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.nio.charset.Charset;
import java.util.Map;

public class CustomRestTemplate {

    public HttpModel get(String url) {
        return get(url, null, null);
    }

    public HttpModel get(String url, Map<String, String> header, String proxyIp) {
        RestTemplate restTemplate;
        if(!StringUtils.isEmpty(proxyIp)) {
            restTemplate = getRestTemplate(proxyIp);
        }else{
            restTemplate = new RestTemplate();
        }
        HttpHeaders httpHeaders = new HttpHeaders();
        if(header != null) {
            header.forEach(httpHeaders::add);
        }
        httpHeaders.add("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
        httpHeaders.add("accept-language", "zh-CN,zh;q=0.9,en;q=0.8");
        HttpEntity<String> httpEntity = new HttpEntity<>(null, httpHeaders);
        HttpModel httpModel = new HttpModel();
        try {
            ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
            httpModel.setCode(responseEntity.getStatusCodeValue());
            httpModel.setContent(responseEntity.getBody());
            return httpModel;
        }catch (Exception e) {
            httpModel.setCode(0);
            httpModel.setContent("");
            return httpModel;
        }
    }


    private RestTemplate getRestTemplate(String proxyIp) {
        String[] proxyArray = proxyIp.split(":");
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyArray[1], Integer.parseInt(proxyArray[2]))));
        return new RestTemplate(factory);
    }


}
